<?php
/**
 * Abstract class that represents the basic DAO Object of the system
 */

class Frogg_DAO{

	const ERROR = -1;
	const ALL   = -1;
	
	public static function createDB(Frogg_Model $obj){
		$fields = '';
		$issetID = false;
		foreach ($obj->getDB() as $property) {
			$fields.= $property.',';
			$issetID = $issetID || ($property->name=='id'); 
		}
		$fields = substr($fields, 0, -1);
		$tablename = $obj->getClass();
		$sql = "
		CREATE TABLE IF NOT EXISTS `".$tablename."` ("
		  .(($issetID)?'':'`id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`),').
		  "$fields
		) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
		";
		new Frogg_Db_Sql("DROP TABLE ".$tablename);
		new Frogg_Db_Sql($sql);
	}
	
	public static function insert(Frogg_Model $obj){
		$class = get_class($obj);
		$table = $obj->getClass();
		$ref = new ReflectionClass($class);
		$properties = $ref->getProperties();
		$fields	 = '';
		$values	 = '';
		$issetID = false;
		foreach ($obj->getDB() as $property) {
			$issetID = $issetID || ($property->name=='id'); 
		}
		foreach ($properties as $property) {
			$name = $property->getName();
			if($name=='id' && !$issetID) continue;
			if($name[0]=='_') continue;
			
			$fields .= '`'.$property->getName().'`,';
			if($obj->$name!='CURRENT_TIMESTAMP'){
				$values .= '\''.addslashes($obj->$name).'\',';
			} else {
				$values .= addslashes($obj->$name).',';
			}
		}
		$fields = substr($fields, 0, -1);
		$values = substr($values, 0, -1);
		
		$sql = new Frogg_Db_Sql("
			INSERT INTO 
				`$table` (".(($issetID)?'':'`id`,')." $fields) 
			VALUES 
				(".(($issetID)?'':'NULL,')."  $values);
		");
		if($sql->getResult()){
			$sql = new Frogg_Db_Sql("
				SELECT
					`id`
				FROM
					`$table`
				ORDER BY
					`id` DESC
				LIMIT
					1;
			");
			$row = $sql->fetch();
			return $row[0];
		}
		return self::ERROR;
	}
	
	public static function update(Frogg_Model $obj){
		$class 		= get_class($obj);
		$table 		= $obj->getClass();
		$ref 		= new ReflectionClass($class);
		$properties = $ref->getProperties();
		$fields_values = ''; 
		foreach ($properties as $property) {
			$name = $property->getName();
			if($name=='id')		continue;
			if($name[0]=='_')	continue;
			
			$value = addslashes($obj->$name);
			$fields_values .= "`$name` = '$value',";
		}
		$fields_values = substr($fields_values, 0, -1);
		new Frogg_Db_Sql("
			UPDATE 
				`$table`
			SET
				 $fields_values
			WHERE
				`id` =$obj->id
			LIMIT
				1;
		");
	}
	
	public static function delete(Frogg_Model $obj){
		$class = get_class($obj);
		$table = $obj->getClass();
		new Frogg_Db_Sql("
			DELETE FROM
				`$table`
			WHERE 
				`id` = $obj->id
			LIMIT 1
		");
	}
	
	public static function load(Frogg_Model &$obj, $id){
		$class = get_class($obj);
		$table = $obj->getClass();
		
		$sql = new Frogg_Db_Sql("
			SELECT
				*
			FROM
				`$table`
			WHERE 
				`id` = $id
		");
		
		if($sql->rows()){
			$row = $sql->fetch();
			$obj->loadData($row);			
			return true;
		}
		return false;
	}
	
	public static function loadField(Frogg_Model &$obj, $field, $value){
		$class = get_class($obj);
		$table = $obj->getClass();
		$value = addslashes($value);
		
		$sql = new Frogg_Db_Sql("
			SELECT
				*
			FROM
				`$table`
			WHERE 
				`$field` = '$value'
		");
		
		if($sql->rows()){
			$row = $sql->fetch();
			$obj->loadData($row);			
			return true;
		}
		return false;
	}
	
	public function getClass(){
		return str_replace('DAO', '', get_class($this));
	}
	
	public function getTable(){
		return strtolower(str_replace('Application_Model_', '',$this->getClass()));
	}
	
	public function count($cond=''){
		$table = $this->getTable();
		
		$sql = new Frogg_Db_Sql("
			SELECT
				*
			FROM
				`$table`
			$cond
		");
		
		return $sql->rows();
	}
	
	public function countField($field=null, $value=null){
		$table = $this->getTable();
		
		$sql = new Frogg_Db_Sql("
			SELECT
				*
			FROM
				`$table`
			WHERE 
				`$field` = '$value'
		");
		
		return $sql->rows();
	}
	
	public function search($amount, $page=1, $cond='',$fields='*',$order_by='') {
		$class = $this->getClass();
		$table = $this->getTable();
		
		$sql = new Frogg_Db_Sql("
			SELECT
				$fields
			FROM
				`$table`
			$cond
			$order_by
			".(($amount==self::ALL)?
				'':
			"LIMIT 
				".(($page-1)*$amount).",$amount")
		);
		$list = array();
		if($sql->rows()){
			while(($row = $sql->fetch())){
				$tmp = new $class();
				$tmp->loadData($row);
				array_push($list, $tmp);
			}
		}
		return $list;
	}
	
	public function countSearch($cond=''){
		$table = $this->getTable();
		
		$sql = new Frogg_Db_Sql("
			SELECT
				*
			FROM
				`$table`
			$cond
		");
		return $sql->rows();
	}
	
	public function navBar($amount, $pg=1, $cond='',$fields='*',$order_by='', $max_pages=5){
		$table = $this->getTable();
		
		$sql = new Frogg_Db_Sql("
			SELECT
				$fields
			FROM
				`$table`
			$cond
			$order_by
		");
		
		$total = $sql->rows();

		if($pg<1) $pg = 1;
		$links = array();			
		
		if($total){
			if($pg == 1){
				$links[1] = 1;
			} else {
				if($pg > 1){
					$links['<<'] = 1;
					$links['<'] = $pg-1;
				}
				
				$num_tmp = $pg - ($max_pages+1);
				
				for($i=1;$i<($max_pages+2);$i++){					
					if(($num_tmp+$i) > 0){
						$links[$num_tmp+$i] = $num_tmp+$i;
					}
				}
			}
			
			$last = ceil($total/$amount);
			
			for($i=1; $i<($max_pages+1);$i++){
				if(($pg+$i) <= $last){
					$links[$pg+$i] = $pg+$i;
				} else {
					break;
				}
			}
			
			if($pg < $last){
				$links['>'] = $pg+1;
				$links['>>'] = $last;
			}				
			
		}
		return $links;
	}
	
}